﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Threading;

namespace PSE.Updater.Common
{
    /// <summary>
    /// Classe responsável por extrair os resources dos Arquivos de Log
    /// </summary>
    [Serializable]
    public class ResourceExtractor : MarshalByRefObject
    {
        private Assembly _assemblyFile;
        public override object InitializeLifetimeService()
        {
            return null;
        }

        /// <summary>
        /// Obtem o conteudo de um arquivo no resource
        /// </summary>
        /// <param name="filePath">Caminho do resource</param>
        /// <param name="resourceFileName">Identificação do resource</param>
        /// <returns>Conteudo do Arquivo</returns>
        public string GetResourceFile(string filePath, string resourceFileName)
        {
            if (_assemblyFile == null)
            {
                _assemblyFile = Assembly.LoadFile(filePath);
            }

            string[] resources = _assemblyFile.GetManifestResourceNames();

            string resource = resources.FirstOrDefault(r => r.EndsWith(resourceFileName));
            if (string.IsNullOrEmpty(resource))
                throw new Exception(string.Format("Não foi possível recuperar o recurso '{0}' no arquivo {1}", resourceFileName, filePath));

            Stream resourceStream = _assemblyFile.GetManifestResourceStream(resource);

            System.IO.StreamReader reader = new System.IO.StreamReader(resourceStream);
            string content = reader.ReadToEnd();
            reader.Close();

            return content;
        }


    }
}
